package com.dhcc.bpm.modules.system.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dhcc.bpm.modules.system.entity.Role;
import com.dhcc.bpm.modules.system.entity.RoleMenu;
import com.dhcc.bpm.modules.system.entity.RoleScope;
import com.dhcc.bpm.modules.system.service.IRoleMenuService;
import com.dhcc.bpm.modules.system.vo.RoleVO;
import com.dhcc.bpm.modules.system.mapper.RoleMapper;
import com.dhcc.bpm.modules.system.service.IRoleScopeService;
import com.dhcc.bpm.modules.system.service.IRoleService;
import lombok.AllArgsConstructor;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.secure.utils.SecureUtil;
import org.springblade.core.tool.constant.BladeConstant;
import org.springblade.core.tool.constant.RoleConstant;
import org.springblade.core.tool.node.ForestNodeMerger;
import org.springblade.core.tool.utils.CollectionUtil;
import org.springblade.core.tool.utils.Func;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import javax.validation.constraints.NotEmpty;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @ClassName RoleServiceImpl
 * @Description  服务实现类
 * @Author sjm
 * @Date 2020/2/21 0021 15:16
 * @Version V1.0
 * @Copyright: 2020 东华软件 . All rights reserved.
 **/
@Service
@Validated
@AllArgsConstructor
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements IRoleService {

	private IRoleMenuService roleMenuService;
	private IRoleScopeService roleScopeService;

	private static Integer DATA_SCOPE_CATEGORY = 1;
	private static Integer API_SCOPE_CATEGORY = 2;

	/**
	 * 自定义分页
	 * @Author sjm
	 * @Date 19:17 2020/2/21 0021
	 * @param page
	 * @param role
	 * @return com.baomidou.mybatisplus.core.metadata.IPage<com.dhcc.bpm.modules.system.vo.RoleVO>
	 **/
	@Override
	public IPage<RoleVO> selectRolePage(IPage<RoleVO> page, RoleVO role) {
		return page.setRecords(baseMapper.selectRolePage(page, role));
	}

	/**
	 * 树形结构
	 * @Author sjm
	 * @Date 19:17 2020/2/21 0021
	 * @param tenantId
	 * @return java.util.List<com.dhcc.bpm.modules.system.vo.RoleVO>
	 **/
	@Override
	public List<RoleVO> tree(String tenantId) {
		String userRole = SecureUtil.getUserRole();
		String excludeRole = null;
		if (!CollectionUtil.contains(Func.toStrArray(userRole), RoleConstant.ADMIN) && !CollectionUtil.contains(Func.toStrArray(userRole), RoleConstant.ADMINISTRATOR)) {
			excludeRole = RoleConstant.ADMIN;
		}
		return ForestNodeMerger.merge(baseMapper.tree(tenantId, excludeRole));
	}

	/**
	 * 权限配置
	 * @Author sjm
	 * @Date 19:17 2020/2/21 0021
	 * @param roleIds
	 * @param menuIds
	 * @param dataScopeIds
	 * @param apiScopeIds
	 * @return boolean
	 **/
	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean grant(@NotEmpty List<Long> roleIds, Map<String,List<Long>> menuIds, Map<String,List<Long>> dataScopeIds, Map<String,List<Long>> apiScopeIds) {
		// 删除角色配置的菜单集合
		roleMenuService.remove(Wrappers.<RoleMenu>update().lambda().in(RoleMenu::getRoleId, roleIds));
		// 组装配置
		for (Map.Entry<String, List<Long>> map : menuIds.entrySet()) {
			String menuKey = map.getKey();
			List<Long> list = map.getValue();
			List<RoleMenu> roleMenus = new ArrayList<>();
			roleIds.forEach(roleId -> list.forEach(menuId -> {
				RoleMenu roleMenu = new RoleMenu();
				roleMenu.setRoleId(roleId);
				roleMenu.setMenuId(menuId);
				if("checked".equals(menuKey)){
					roleMenu.setType("1");
				}else{
					roleMenu.setType("2");
				}
				roleMenus.add(roleMenu);
			}));
			// 新增配置
			roleMenuService.saveBatch(roleMenus);
		}


		// 删除角色配置的数据权限集合
		roleScopeService.remove(Wrappers.<RoleScope>update().lambda().eq(RoleScope::getScopeCategory, DATA_SCOPE_CATEGORY).in(RoleScope::getRoleId, roleIds));
		// 组装配置
		for (Map.Entry<String, List<Long>> map : dataScopeIds.entrySet()) {
			String scopeKey = map.getKey();
			List<Long> list = map.getValue();
			List<RoleScope> roleDataScopes = new ArrayList<>();
			roleIds.forEach(roleId -> list.forEach(scopeId -> {
				RoleScope roleScope = new RoleScope();
				roleScope.setScopeCategory(DATA_SCOPE_CATEGORY);
				roleScope.setRoleId(roleId);
				roleScope.setScopeId(scopeId);
				if("checked".equals(scopeKey)){
					//全选
					roleScope.setType("1");
				}else{
					//半选
					roleScope.setType("2");
				}
				roleDataScopes.add(roleScope);
			}));
			// 新增配置
			roleScopeService.saveBatch(roleDataScopes);
		}

		// 删除角色配置的数据权限集合
		roleScopeService.remove(Wrappers.<RoleScope>update().lambda().eq(RoleScope::getScopeCategory, API_SCOPE_CATEGORY).in(RoleScope::getRoleId, roleIds));
		// 组装配置
		for (Map.Entry<String, List<Long>> map : apiScopeIds.entrySet()) {
			String scopeKey = map.getKey();
			List<Long> list = map.getValue();
			List<RoleScope> roleApiScopes = new ArrayList<>();
			roleIds.forEach(roleId -> list.forEach(scopeId -> {
				RoleScope roleScope = new RoleScope();
				roleScope.setScopeCategory(API_SCOPE_CATEGORY);
				roleScope.setScopeId(scopeId);
				roleScope.setRoleId(roleId);
				if("checked".equals(scopeKey)){
					//全选
					roleScope.setType("1");
				}else{
					//半选
					roleScope.setType("2");
				}
				roleApiScopes.add(roleScope);
			}));
			// 新增配置
			roleScopeService.saveBatch(roleApiScopes);
		}

		return true;
	}

	/**
	 * 获取角色名
	 * @Author sjm
	 * @Date 19:17 2020/2/21 0021
	 * @param roleIds
	 * @return java.util.List<java.lang.String>
	 **/
	@Override
	public List<String> getRoleNames(String roleIds) {
		return baseMapper.getRoleNames(Func.toStrArray(roleIds));
	}

	/**
	 * 获取角色名
	 * @Author sjm
	 * @Date 19:17 2020/2/21 0021
	 * @param roleIds
	 * @return java.util.List<java.lang.String>
	 **/
	@Override
	public List<String> getRoleAliases(String roleIds) {

		return baseMapper.getRoleAliases(Func.toLongArray(roleIds));
	}

	/**
	 * 提交
	 * @Author sjm
	 * @Date 19:18 2020/2/21 0021
	 * @param role
	 * @return boolean
	 **/
	@Override
	public boolean submit(Role role) {
		if (!SecureUtil.isAdministrator()) {
			if (Func.toStr(role.getRoleAlias()).equals(RoleConstant.ADMINISTRATOR)) {
				throw new ServiceException("无权限创建超管角色！");
			}
		}
		if (Func.isEmpty(role.getParentId())) {
			role.setParentId(BladeConstant.TOP_PARENT_ID);
		}
		role.setIsDeleted(BladeConstant.DB_NOT_DELETED);
		return saveOrUpdate(role);
	}
	/**
	 * 根据roleIds查询roleName和Id
	 * @Author sjm
	 * @Date 19:18 2020/2/21 0021
	 * @param roleIds
	 * @return java.util.List<com.dhcc.bpm.modules.system.entity.Role>
	 **/
	@Override
	public List<Role> getRoleSelectByIds(String roleIds) {
		return baseMapper.getRoleSelectByIds(Func.toStrArray(roleIds));
	}

	@Override
	public List<Role> getByParentId(String parentId) {
		return baseMapper.getByParentId(parentId);
	}

	/**
	 * 根据roleIds查询roleName和Id
	 * @Author sjm
	 * @Date 19:18 2020/2/21 0021
	 * @param roleId
	 * @return java.util.List<com.dhcc.bpm.modules.system.entity.Role>
	 **/
	@Override
	public boolean removeByRoleId(Long roleId) {
		return baseMapper.removeByRoleId(roleId);
	}
}
